var laguage = document.querySelectorAll(".language");
var choiceLanguage = document.querySelector("#choiceLanguage");

window.onload = function () {
    var ajax = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
    ajax.open("GET", ROOTSources + "/program/isCollect/" + customerId + "/" + programId, true);
    ajax.send();
    ajax.onreadystatechange = function () {
        if (ajax.readyState === 4) {
            if (ajax.status >= 200 && ajax.status < 300 || ajax.status === 304) {
                var result = JSON.parse(ajax.responseText);
                if (result.data.programCollectTime != null) {
                    collect.innerText = "已收藏";
                    collect.setAttribute("class", "btn btn-success");
                } else {
                    collect.innerText = "收藏";
                    collect.setAttribute("class", "btn btn-info");
                }
            }
        }
    }
};

function styleC() {
    editor.setValue(`
#include <stdio.h>

int main(${params}){
    
}`);
    editor.setOption("mode", "text/x-csrc")
}//C语言默认样式
function styleCadd() {
    editor.setValue(`class Solution {
public:
    int main(${params}) {
        
    }
};`);
    editor.setOption("mode", "text/x-c++src")
}//C++默认样式
function styleJava() {
    editor.setValue(`
public ${returnType} run(${params}){
             
}`);
    editor.setOption("mode", "text/x-java")
}//Java默认样式
function styleJavaScript() {
    editor.setValue(`var result = function() {
    
};`);
    editor.setOption("mode", "javascript")
}//JS默认样式
//不同语言下，编译器高亮
for (var i = 0; i < laguage.length; i++) {
    laguage[i].onclick = function () {
        choiceLanguage.innerText = this.innerText;
        switch (choiceLanguage.innerText) {
            case "C":
                sendContent.judgeId = 1;
                styleC();
                break;
            case "Java":
                sendContent.judgeId = 8;
                styleJava();
                break;
            case "JavaScript":
                sendContent.judgeId = 11;
                styleJavaScript();
                break;
            case "C++":
                sendContent.judgeId = 4;
                styleCadd();
                break;
        }
    };
}

let app = document.querySelector("#app");
//在线编译器
let editor = CodeMirror.fromTextArea(app, {
    lineNumbers: true, //显示行数
    theme: 'idea',    //主题
    lint: true,

    spellcheck: true, //指定是否在输入上启用拼写检查。
    autocorrect: true, //指定是否在输入上启用自动更正。
    autocapitalize: true, //指定是否在输入上启用自动大写。

    tabSize: 4,
    // theme: "3024-night",
    styleActiveLine: true,
    line: true,
    foldgutter: true,
    gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter", "CodeMirror-lint-markers"],
    lineWrapping: true, //代码折叠         
    foldGutter: true,
    matchBrackets: true,  //括号匹配         
    autoCloseBrackets: true
});
//默认样式
styleC();
//点击返回主页
var back = document.querySelector("#returnList");
back.onclick = function () {
    window.location.href = ROOTSources + "/program";
};
//点击恢复默认样式
var backDefault = document.querySelector("#backDefault");
backDefault.onclick = function () {
    switch (choiceLanguage.innerText) {
        case "C":
            styleC();
            break;
        case "Java":
            styleJava();
            break;
        case "JavaScript":
            styleJavaScript();
            break;
        case "C++":
            styleCadd();
            break;
    }
};

var inputContent=sendContent.input[0].split(" ");
console.log(inputContent);
var before = new Number(inputContent[0]);
var end = new Number(inputContent[1]);
console.log(before);
console.log(end);
var javaTitle = `class Main{ public static void main(String args[]){
System.out.print(new Main().run(${before+","+end}));}`;
var javaFoot = `}`;
//点击执行代码
var performBtn = document.querySelector("#performBtn");
performBtn.onclick = function () {
    sendContent.src = javaTitle + editor.getValue().replace("\n", "\n\t") +javaFoot;
    console.log(sendContent.src);
    var ajax = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
    ajax.open("POST", ROOTSources + "/contest/performCode", true);
    ajax.setRequestHeader("Content-Type", "application/json");
    ajax.send(JSON.stringify(sendContent));
    ajax.onreadystatechange = function () {
        if (ajax.readyState === 4) {
            if (ajax.status >= 200 && ajax.status < 300 || ajax.status === 304) {
                var jsonResult = JSON.parse(ajax.responseText);
                console.log(jsonResult);
                localStorage.setItem("recentCode", editor.getValue());
                if (jsonResult.globalMsg != null || jsonResult.result[0].status !== 0) {
                    alert("对不起答案错误！");
                } else {
                    alert("执行正确，可提交")
                }
            }
        }
    }
};
//点击获取最近执行代码
var getRecentCode = document.querySelector("#getRecentCode");
getRecentCode.onclick = function () {
    editor.setValue(localStorage.getItem("recentCode"));
};
//点击提交代码
var submitCode = document.querySelector("#submitBtn");
submitCode.onclick = function () {
    sendContent.src = javaTitle + editor.getValue().replace("\n", "\n\t") +javaFoot;
    var ajax = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
    ajax.open("POST", ROOTSources + "/program/submitProgram/" + customerId + "/" + programId, true);
    ajax.setRequestHeader("Content-Type", "application/json");
    ajax.send(JSON.stringify(sendContent));
    ajax.onreadystatechange = function () {
        if (ajax.readyState === 4) {
            if (ajax.status >= 200 && ajax.status < 300 || ajax.status === 304) {
                alert("提交成功");
            }
        }
    }
};

var goLast = document.querySelector("#goLast");
var goNext = document.querySelector("#goNext");

if (programId <= 1) {
    //上一题
    goLast.disabled = "disabled";
}
if (programId + 1 > programSize) {
    //下一题
    goNext.disabled = "disabled";
}
goLast.onclick = function () {
    window.location.href = ROOTSources + "/program/goProgram/" + (programId - 1);
};
goNext.onclick = function () {
    window.location.href = ROOTSources + "/program/goProgram/" + (programId + 1);
};
//收藏按钮
var collect = document.querySelector("#collect");
collect.onclick = function () {
    var ajax = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
    ajax.open("GET", ROOTSources + "/program/collect/" + customerId + "/" + programId, true);
    ajax.send();
    ajax.onreadystatechange = function () {
        if (ajax.readyState === 4) {
            if (ajax.status >= 200 && ajax.status < 300 || ajax.status === 304) {
                let result = JSON.parse(ajax.responseText);
                if (result.status === 1) {
                    if (result.data === 1) {
                        collect.innerText = "已收藏";
                        collect.setAttribute("class", "btn btn-success");
                    } else {
                        collect.innerText = "收藏";
                        collect.setAttribute("class", "btn btn-info");
                    }
                }
            }
        }
    }
};
//前往讨论区
var goComment = document.querySelector("#goComment");
goComment.onclick = function () {
    window.location.href = ROOTSources + "/program/goComment/" + programId;
};